// pages/login/login.js
const app = getApp();
const request = require('../../utils/request.js');
const config = require('../../utils/config.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        topBarHeight: 0, //顶部导航高度
        Pop:false,
        Pop2:false,
        backup:1,
        login:1,
        avatarUrl:'',
        nickName:'',
        logo:'/static/icon/logo_mini.png',
        showPrivacy: false,
        privacy:'',
        privacyContractName:'《新眼光健康管理小程序隐私保护指引》'
    },
    getBarInfo(e) {
        console.log(e.detail.topBarHeight);
        this.setData({
          topBarHeight: e.detail.topBarHeight
        })
      },
    onChooseAvatar(e) {
        const { avatarUrl } = e.detail 
        var that =this;
     
           wx.uploadFile({
            url: config.web_url + '/api/common/ossupload',
            filePath: avatarUrl,
            name: 'file',
            header: {
                "Content-Type": "multipart/form-data",
                'token': wx.getStorageSync('token')
            },
            success: function (res) {
                var data = JSON.parse(res.data);
                console.log(data)
                if(data.msg=='上传成功'){
                    that.setData({
                       avatarUrl:data.data.fullurl
                    })
                    
                    return
                }else{
                    wx.showToast({
                      title: data.msg,
                      icon:'none'
                    }) 
                    return
                }
              
             
               
               
            },
            fail:function(res){
                console.log(res)
            }
        })
       
      },
      inputNickname(e){
        this.setData({
            nickName:e.detail.value
        })
      },
     cancelshou(){
       this.setData({
        showPopup3:false
       })
     },
     submitProfile(){
       var   that =this;
         var userInfo={'avatarUrl':that.data.avatarUrl,'nickName':that.data.nickName};
         if(!userInfo.avatarUrl){
            wx.showToast({
              title: '请选择头像！',
              icon:'none'
            })
            return false
        }
        if(!userInfo.nickName){
          wx.showToast({
              title: '请输入昵称！',
              icon:'none'
            })
            return false
        }
          var that = this;
          request.requestLoading(
              "/api/login/getUserMessage",
              {
                openid:wx.getStorageSync('openid'),
                userInfo:JSON.stringify(userInfo),
              },
              'POST',
            ).then((res) => {
               if(res.code){
                wx.setStorageSync('thirdInfo', res.data)
                that.setData({
                    auth_type:2,
                    Pop2:!that.data.Pop2
                  })
                  return;
               }else{
                 wx.showToast({
                   title: res.msg,
                   icon:'none'
                 })
                 return;
               }
             
             
        
            }).catch((err) => {
              console.error(err);
            });
     },
    gocancel(){
     this.setData({
        Pop2: !this.data.Pop2
     })
    },
    Check_Login(){
        var that=this;
        wx.login({
            success: function (res) {
            if (res.code) {
                request.requestLoading(
                    "/api/login/checklogins",
                    {  code: res.code,},
                    'POST',
                  ).then((res) => {
                    if (res.code == 1) {
                        if(res.data==4){
                            wx.navigateBack({
                                delta:1
                            })
                        }else{
                            that.setData({
                                auth_type:res.data
                            })
                        }
                       
                      } else {
                        functions.toast(res.msg)
                       
                      }
            
                   
                     
              
                  }).catch((err) => {
                    console.error(err);
                  });
              
              } else {
                console.log("用户失败")
              }
            }
          });
     
      },
      // 取消授权返回上一页
  cancelAuth(){
    wx.navigateBack();
  },
  gologoin(){
    wx.login({
        success: function (res) {
         
          if (res.code) {
          
              wx.showLoading({
                title: '登录中...',
              })
            
            request.requestLoading(
                "/api/login/userLogin",
                {
                  code: res.code,

                },
                'POST',
                true,
            ).then((res) => {
              console.log(res)
              wx.hideLoading();
             


              if (res.code == 1) {
                console.log(112)
                if (res.data.need_login_type == 2) {
                  wx.setStorageSync('token', '');
                  wx.setStorageSync('openid', res.data.openid);
                  if(res.data.authorization_status==2){
                    wx.setStorageSync('authorization_status', res.data.authorization_status)
                  }
    
                } else {
                  wx.setStorageSync('openid', res.data.openid);
                  wx.setStorageSync('token', res.data.userinfo.token);
                  wx.setStorageSync('mobile', res.data.userinfo.mobile);
                  wx.setStorageSync('userInfo', res.data.userinfo)

                  getApp().globalData.userInfo = res.data.userinfo;
                  
                }
                console.log(112)
                wx.navigateBack({
                    delta:1
                })
                
              } else {
                wx.showToast({
                    title: res.msg,
                    icon: 'text',
                    duration:2000
                  });
              }
            }).catch((err) => {
              // wx.showModal({
              //   title: '温馨提示',
              //   content: err.errMsg,
              //   showCancel: false
              // });
              wx.hideLoading()
         
            });
          } else {
            console.log("用户失败")
          }
        }
      });
  },
      // 弹窗
  togglePop(e){
      
      this.setData({
        Pop2: !this.data.Pop2
    });
   
},
bindGetPhoneNumber(e){
    var that = this;
   
    if (e.detail.errMsg == 'getPhoneNumber:fail: user deny'||e.detail.errMsg=='getPhoneNumber:fail:user cancel'){
        wx.showModal({
          title: '温馨提示',
          content: '您已拒绝授权，无法获取手机号！',
          showCancel: false,
          success: function(res){
            if(res.confirm){
              wx.navigateBack();
            }
          }
        });
        return;
    } else {
       
        if(e.detail.errMsg=="getPhoneNumber:fail no permission"){
            wx.showToast({
              title: '没有权限',
              icon:'none'
            })
            return false
        }
      app.decryptPhoneNumber(e.detail, function () {
        wx.navigateBack();
      });
    }
  },
      // 弹窗
      togglePop2(e){
        this.setData({
            Pop2: !this.data.Pop2
        });
    },
    togglePop3(e){
        this.setData({
            showPrivacy: !this.data.showPrivacy
        });
    },
nameChange: function (event) {
    const name = event.detail || event;
    let message = '';
    let disable = '';
    if(name) {
      if (/^[\u4e00-\u9fa5]{2,6}$/.test(name)){
        message = '';
        disable = false;
      } else {
        message = '输入的用户名有误';
        disable = true;
      }
    } else {
      message = '输入的用户名有误',
        disable = true
    }
    this.setData({
      nameMessage: message,
      disabled: disable,
      acc_name: name
    });
    if (this.data.disabled === true) {
      return false;
    }else {
      return true;
    }
  },
  telChange: function (event) {
    const password = event.detail || event;
    let message = '';
    let disable = '';
    if (password) {
      if (/^[0-9a-zA-Z]{6}$/.test(password)) {
        message = '';
        disable = false;
      } else {
        message = '您输入的密码有误';
        disable = true;
      }
    } else {
      message = '输入的密码不能为空',
      disable = true
    }
    this.setData({
      telMessage: message,
      disabled: disable,
      txn_tel: password
    });
    if (this.data.disabled === true) {
      return false;
    }else {
      return true;
    }
  },
  handleAgreePrivacyAuthorization() {
     if(this.data.auth_type==1){
        this.setData({
            showPrivacy: false,
            Pop2:true
          })
     }
    else if(this.data.auth_type==2){
        this.setData({
            showPrivacy: false
          })
     }
  },
  handleOpenPrivacyContract() {
    // 打开隐私协议页面
    wx.openPrivacyContract({
      success: () => {}, // 打开成功
      fail: () => {}, // 打开失败
      complete: () => {}
    })
  },
  checkPrivacy(){
      var is_return=false;
    wx.getPrivacySetting({
        success: res => {
          console.log(res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
          if (res.needAuthorization) {
            // 需要弹出隐私协议
            this.setData({
              showPrivacy: true,
              privacyContractName:res.privacyContractName
            })
            is_return=false;
        
          } else {
            is_return=true;
         
          }
        },
        fail: () => {},
        complete: () => {}
      })
      return is_return;
  },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        app.init_config().then((res) => {
            this.setData({
              logo:res.logo,
              privacy:res.privacy,
              is_show:true
            })
          });
      
          app.init_userInfo().then((res) => {
            wx.setStorageSync('userInfo', res)
            this.setData({
              userInfo: res
            })
          });
          this.Check_Login();
        
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

})